package com.loong.musicdemo.util.downloadutil;

import android.os.AsyncTask;
import android.os.Environment;

import com.loong.musicdemo.model.LocalPlay;
import com.loong.musicdemo.model.Song;
import com.loong.musicdemo.util.dataDeal.MusicDeal;

import org.litepal.LitePal;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.Objects;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 下载服务子线程
 */
public class DownloadTask extends AsyncTask<String, Integer, Integer> {
    private static final int TYPE_SUCCESS = 0;
    private static final int TYPE_FAILED = 1;
    private static final int TYPE_PAUSED = 2;
    private static final int TYPE_CANCELED = 3;
    private DownloadListener listener;
    private boolean isCanceled = false;
    private boolean isPaused = false;
    private int lastProgress;

    public DownloadTask(DownloadListener listener) {
        this.listener = listener;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        int progress = values[0];
        if (progress > lastProgress) {
            listener.onProgress(progress);
            lastProgress = progress;//刷新进度
        }
    }

    @Override
    protected Integer doInBackground(String... strings) {
        InputStream is = null;
        RandomAccessFile rw = null;//随机存储
        File file = null;//存储文件
        String id = strings[0];//获取歌曲id
        Song info = MusicDeal.getSongInfoById(id);
        String playUrl = info.getPlayUrl();//播放地址
        if (!(playUrl.startsWith("https") || playUrl.startsWith("http"))) {
            //请求头错误，或者不存在下载播放地址
            return TYPE_FAILED;//下载失败
        } else {
            //开始进行下载
            try {
                String directory = Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                        .getPath() + "/mymusic/";//存储文件夹
                String fileName = id + playUrl.substring(playUrl.lastIndexOf("."));
                file = new File(directory);
                boolean mkdir = true;
                if (!file.exists()) {
                    mkdir = file.mkdir();//创建文件夹
                }
                if (mkdir) {
                    file = new File(directory + "/" + fileName);
                    long downloadedLength = 0;
                    if (file.exists()) {
                        downloadedLength = file.length();//存在说明下载过
                    }
                    long contentLength = SongDownload.getContentLength(playUrl);
                    if (contentLength == 0) {
                        //下载失败
                        return TYPE_FAILED;
                    } else if (contentLength == downloadedLength) {
                        //下载完成
                        return TYPE_SUCCESS;
                    }
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            //断点下载
                            .addHeader("RANGE", "bytes=" + downloadedLength + "-")
                            .url(playUrl)
                            .build();
                    Response response = client.newCall(request).execute();
                    is = Objects.requireNonNull(response.body()).byteStream();
                    //继续下载
                    byte[] buf = new byte[1024];
                    rw = new RandomAccessFile(file, "rw");
                    rw.seek(downloadedLength);//跳过已下载的字节
                    int len = 0;
                    long current = 0;
                    while ((len = is.read(buf)) != -1) {
                        if (isCanceled) {
                            return TYPE_CANCELED;
                        } else if (isPaused) {
                            return TYPE_PAUSED;
                        } else {
                            current += len;
                            rw.write(buf, 0, len);
                            //计算已经下载百分比
                            int progress = (int) ((current + downloadedLength) * 100 / contentLength);
                            publishProgress(progress);
                        }

                    }
                    Objects.requireNonNull(response.body()).close();
                    return TYPE_SUCCESS;//下载成功
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (is != null) {
                        is.close();
                    }
                    if (rw != null) {
                        rw.close();
                    }
                    if (isCanceled && file != null) {
                        file.delete();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return TYPE_FAILED;
    }

    @Override
    protected void onPostExecute(Integer integer) {
        switch (integer) {
            case TYPE_SUCCESS:
                listener.onSuccess();
                break;
            case TYPE_FAILED:
                listener.onFailed();
                break;
            case TYPE_PAUSED:
                listener.onPaused();
                break;
            case TYPE_CANCELED:
                listener.onCanceled();
                break;
            default:
                break;

        }
    }

    public void pauseDownload() {
        isPaused = true;
    }

    public void cancelDownload() {
        isCanceled = true;
    }
}
